/**
 * 样衣初选单
 */
import * as React from 'react'
import { Card, Form, Select, Input, Button, Icon, Row, Col, message, TreeSelect } from 'antd'
import Authentication from '../../router/Authentication'
import { FormComponentProps } from 'antd/lib/form/Form'
import { PageHeaderLayout, DescriptionList, Description, Zmage } from '../../components'
import '../../assets/style/detail.less'
import { post, SUBMIT_DETAIL } from '../../service/api'
const FormItem = Form.Item
// const TreeNode = TreeSelect.TreeNode
const { Option } = Select
export interface Props{
  record: any
  sample: any
  sampleImgs: any
  workStatus: any []
  checkList: any []
  roleScore: any []
  sampleScore: any []
  colors: any []
  sizes: any []
  history: any
}

export interface State {
  mainColors: any []
  mainSizes: any []
  detail: any
}

let uuid = 0
@Authentication
class PrimaryForm extends React.Component<Props & FormComponentProps, State> {

  state = {
    mainColors: [],
    mainSizes: [],
    detail: {}
  }
  componentDidMount () {
    uuid = 0
  }
  componentWillReceiveProps (nextProps: Props & FormComponentProps) {
    const { record } = nextProps
    const { detail } = this.state
    if(JSON.stringify(record) !== JSON.stringify(detail)) {
      this.review(record)
    }
  }

  //数据回显
  review = (record: any) => {
    const { form } = this.props
    let mainColors: any [] = []
    let mainSizes: any [] = []
    let Color: any [] = []
    let Size: any [] = []
    let OneColor: any [] = []
    let color: any [] = []
    let size: any [] = []
    let num: any [] = []
    let keys: any [] = []
   
    record.Detial.map((detail: any) => {
      keys = [...keys, uuid]
      color = [...color, detail.ColorId]
      size = [...size, detail.SizeId]
      num = [...num, detail.sendqty]
      uuid++
    })
    form.setFieldsValue({
      keys
    })
    record.Color.map((color: any) => {
      mainColors = [...mainColors, {
        value: color.colourid,
        label: color.colourname
      }]
      if(color.isrecom == 1)
        OneColor = [...OneColor, color.colourid]
      Color = [...Color, color.colourid]
    })
    record.Size.map((size: any) => {
      mainSizes = [...mainSizes, {
        value: size.sizeid,
        label: size.sizename
      }]
      Size = [...Size, size.sizeid]
    })
    this.setState({
      ...this.state,
      detail: record,
      mainColors,
      mainSizes
    })
    setTimeout(() => {
      this.handleChangeMainColor(OneColor)
      form.setFieldsValue({
        Color,
        Size,
        OneColor,
        color,
        size,
        num,
        cost: record.cost
      })
    }, 0)
  }
  filterTree = (treeValue: any []): any => {
    if(treeValue.length>0){
      let v: any [] = []
      treeValue.map((row: any) => {
        let record: any = row
        if(record.children){
          record.disabled = true
          record.children = this.filterTree(record.children)
        }else  {
          record.disabled = false
        }
        v = [...v, record]
      })
      return v
    }
  }
  handleSave = (e: any) => {
    e.preventDefault()
    const { form, sample } = this.props
    const { mainColors, mainSizes } = this.state
    form.validateFields((err: any, values: any) => {
      if (err) return
      let param: any = {}
      let Color: any [] = []
      let Size: any [] = []
      let Detial: any [] = []
      mainColors.map((row: any) => {
        Color = [...Color, {
          colourid: row.value,
          colourname: row.label,
          isrecom: values.OneColor.contains(row.value)? 1 : 0,
          note: ''
        }]
      })
      mainSizes.map((row: any) => {
        Size = [...Size, {
          sizeid: row.value,
          sizename: row.label,
          note: ''
        }]
      })
      values.keys.map((row: number, index: number) => {
        Detial = [...Detial, {
          ColorId: values.color[index],
          SizeId: values.size[index],
          SendNum: values.num[index]
        }]
      })
      param.sampleId = sample.sampleId
      param.ids = { cost: values.cost, Color, Size, Detial }
      post(SUBMIT_DETAIL, param).then((res: any) => {
        if (res.code == '1') {
          message.success('操作成功！')
          this.props.history.goBack()
        }else {
          message.error(res.errMsg)
        }
      })
    })
  }
  changeColor = (key: any [], value: any []) => {
    let mainColors: any [] = []
    key.map((row: any, index: number) => {
      mainColors = [...mainColors, {
        label: value[index],
        value: row,
        
      }]
    })
    this.setState({
      ...this.state,
      mainColors
    })
  }
  changeSize = (key: any [], value: any []) => {
    let mainSizes: any [] = []
    key.map((row: any, index: number) => {
      mainSizes = [...mainSizes, {
        label: value[index],
        value: row
      }]
    })
    this.setState({
      ...this.state,
      mainSizes
    })
  }
  //动态删除
  remove = (k: number) => {
    const { form } = this.props
    const keys = form.getFieldValue('keys');
    if (keys.length === 1) {
      return
    }
    form.setFieldsValue({
      keys: keys.filter((key: number) => key !== k),
    })
  }
  //动态添加
  add = () => {
    const { form } = this.props;
    const keys = form.getFieldValue('keys')
    const nextKeys = keys.concat(uuid)
    uuid++
    form.setFieldsValue({
      keys: nextKeys,
    })
  }
  handleChangeMainColor = (e: any []) => {
    const { mainColors } = this.state
    let newMc = mainColors
    if(e.length>1) {
      newMc.map((row: any) => {
        if(!e.contains(row.value)){
          row.disabled = true
        }
      })
    }else {
      newMc.map((row: any) => {
        row.disabled = false
      })
    }
    this.setState({
      ...this.state,
      mainColors: newMc
    })
  }
  render () {
    const { sampleImgs, sample, form, colors, sizes } = this.props
    const { getFieldDecorator, getFieldValue } = form
    const { mainColors, mainSizes } = this.state
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 34 },
        sm: { span: 12 },
        md: { span: 15 },
      },
    }
    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    }
    const getImgs = () => {
      let imgs = []
      if(sampleImgs) {
        if(sampleImgs.limg1) imgs.push(sampleImgs.limg1)
        if(sampleImgs.limg2) imgs.push(sampleImgs.limg2)
        if(sampleImgs.limg3) imgs.push(sampleImgs.limg3)
        if(sampleImgs.limg4) imgs.push(sampleImgs.limg4)
        if(sampleImgs.limg5) imgs.push(sampleImgs.limg5)
      }
      return imgs
    }
    getFieldDecorator('keys')
    const keys = getFieldValue('keys') || []
    const formItems = keys.map((k: number, index: number) => {
      return (<div key={k} style={{marginLeft: "20.83333333%", width: "65%"}}>
          <Row gutter={24}>
            <Col span={7}>
              <FormItem>
                {getFieldDecorator(`color[${k}]`, { rules: [{ required: true, message: '请选择' }],})(
                  <Select placeholder="请选择颜色">
                    {mainColors.map( (mc: any, l: number) => (
                      <Option key={l} value={mc.value}>{mc.label}</Option>
                    ))}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={7}>
              <FormItem>
                {getFieldDecorator(`size[${k}]`, { rules: [{ required: true, message: '请选择' }]})(
                  <Select placeholder="请选择尺寸">
                    {mainSizes.map( (ms: any, j: number) => (
                      <Option key={j} value={ms.value}>{ms.label}</Option>
                    ))}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={7}>
              <FormItem>
                {getFieldDecorator(`num[${k}]`, { rules: [{ required: true, message: '请选择' }]})(
                  <Input placeholder="填写数量" style={{ marginRight: 8 }} />
                )}
              </FormItem>
            </Col>
            <Col span={3}>
              <FormItem>
                {keys.length > 1 ? (
                  <Icon
                    className="dynamic-delete-button"
                    type="minus-circle-o"
                    onClick={() => this.remove(k)}
                  />
                ) : null}
              </FormItem>
            </Col>
          </Row>
        </div>
      )
    })
    return (
      <PageHeaderLayout 
        title = "">
        <Card bordered  title="基本资料">
          <DescriptionList size="large" title="样衣图片" style={{ marginBottom: 32 }}>
            <Description term="" style={{width: "100%"}}>
              {getImgs().map((img: string, index: number) => (
                <Zmage key={index} className="yy-img" src={img} />
              ))}
            </Description>
          </DescriptionList>
          <DescriptionList size="large" title="样衣信息" style={{ marginBottom: 32 }}>
            <Description term="样衣编码">{sample.sampleId}</Description>
            <Description term="波段号">{sample.bandname}</Description>
            <Description term="大类">{sample.dlText}</Description>
            <Description term="小小类">{sample.xlText}</Description>
            <Description term="供应商货号">{sample.pcode}</Description>
            <Description term="合作方式">{sample.jyfs}</Description>
            <Description term="供应商编码">{sample.supplierid}</Description>
            <Description term="供应商名称">{sample.vendername}</Description>
          </DescriptionList>
        </Card>
        <Card bordered style = {{marginTop: "10px"}} title="邮寄信息">
        <Form onSubmit={this.handleSave} hideRequiredMark style={{ marginTop: 8 }}>
            <FormItem label="颜色" {...formItemLayout}>
              {getFieldDecorator('Color', { rules: [{ required: true, message: '请选择颜色' }]})(
                <TreeSelect
                  showSearch
                  treeData = {this.filterTree(colors)}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder="请选择颜色"
                  allowClear
                  multiple
                  onChange={this.changeColor}
                />
              )} 
            </FormItem>
            <FormItem label="主荐颜色" {...formItemLayout}>
              {getFieldDecorator('OneColor', { rules: [{ required: true, message: '请选择主荐颜色' }]})(
                <Select 
                  placeholder="请选择主荐颜色" 
                  showSearch 
                  mode="multiple" 
                  onChange={this.handleChangeMainColor}>
                  {mainColors.map( (mc: any, l: number) => (
                    <Option disabled={mc.disabled} key={l} value={mc.value}>{mc.label}</Option>
                  ))}
                </Select>
              )} 
            </FormItem>
            <FormItem label="尺码" {...formItemLayout}>
              {getFieldDecorator('Size', { rules: [{ required: true, message: '请选择尺码' }]})(
                <TreeSelect
                  showSearch
                  treeData = {this.filterTree(sizes)}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder="请选择尺码"
                  allowClear
                  multiple
                  onChange={this.changeSize}
                />
              )} 
            </FormItem>
            <FormItem label="报价" {...formItemLayout}>
              {getFieldDecorator('cost', { rules: [{ required: true, message: '请输入报价' }]})(
                <Input placeholder="请输入报价"/>
              )} 
            </FormItem>
            <FormItem label="邮寄数量" {...formItemLayout}>
              <Icon onClick={this.add} type="plus-circle-o" />
            </FormItem>
            {formItems}
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={()=>{this.props.history.goBack()}} >返回</Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout>
    )
  }
}
export default Form.create()(PrimaryForm)
